﻿using AutoMapper;
using Common.Log;
using DryWCS.Biz.Mapper;
using DryWCS.Service.Conveyor;
using DryWCS.Service.Flatcar;
using DryWCS.Service.Stacker;
using Sharp7;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DryWCS.Biz.Base
{
    public class MachineBase
    {
       // protected WMSCommandService wmsCommandService = new WMSCommandService();
        protected StackerTaskService stackerTaskService = new StackerTaskService();
        protected StackerTaskHisService stackerTaskHisService = new StackerTaskHisService();
        protected FlatcarTaskService flatcarTaskService = new FlatcarTaskService();
        protected FlatcarTaskHisService flatcarTaskHisService = new FlatcarTaskHisService();
        protected ConveyorTaskService conveyorTaskService = new ConveyorTaskService();
        protected ConveyorTaskHisService conveyorTaskHisService = new ConveyorTaskHisService();
    
        protected readonly IMapper mapper;

        public S7Client client { get; set; } = new S7Client();

        public PLCInfo PLCInfo { get; set; }

        public MachineBase(PLCInfo plcInfo)
        {
            var config = new MapperConfiguration(cfg => cfg.AddProfile(new MapperFile()));
            mapper = config.CreateMapper();

            PLCInfo = plcInfo;
        }

        public virtual void Connect()
        {
            try
            {
                if (client == null)
                {
                    client = new S7Client();
                }
                client.ConnTimeout = 4000;
                int res = 0;
                if (!client.Connected)
                {
                    res = client.ConnectTo(PLCInfo.IP, PLCInfo.Rack, PLCInfo.Slot);
                }

                if (res != 0)
                {
                    LogHelper.WriteLog($"{PLCInfo.Name}连接异常。", new Exception($"{client.ErrorText(res)}"));
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"{PLCInfo.Name}连接异常。", ex);
            }
        }

        public virtual void Read()
        {
        }


        protected bool Retry<T>(int times, Func<T, bool> func, T para)
        {
            int retryTimes = 0;
            while (true)
            {
                bool res = func.Invoke(para);
                retryTimes++;

                if (res || retryTimes >= times)
                {
                    return res;
                }
                Thread.Sleep(100);
            }
        }

        protected bool Retry(int times, Func<bool> func)
        {
            int retryTimes = 0;
            while (true)
            {
                bool res = func.Invoke();
                retryTimes++;

                if (res || retryTimes >= times)
                {
                    return res;
                }
                Thread.Sleep(100);
            }
        }
    }
}
